package ru.hh.team02.chat.clientComputer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientReader implements Runnable {
    private final static int SERVER_PORT = 2004;
    private final static int LOCAL_PORT = 5555;

    private StringSocket serverChannel;
    private StringSocket localChannel;
    private String serverName;
    private int localPort;
    
    public static void main(String[] args) {
		int localPort;
		if (args.length == 0) {
			System.out.println("Parameter server name is needed");
			System.exit(0);
		}
		if (args.length == 1) {
			localPort = LOCAL_PORT;
		} else {
			localPort = Integer.parseInt(args[1]);
		}
		new ClientReader(args[0], localPort).run();
    }

	public ClientReader(String serverName, int localPort) {
		this.serverName = serverName;
		this.localPort = localPort;
	}
	
	@Override
    public void run() {
        try {
            serverChannel = new StringSocket(new Socket(serverName, SERVER_PORT));
            System.out.println("connected to " + serverName + " in port " + SERVER_PORT);
            startWriterListener();
            String message = "";
            do {                
                System.out.println(serverChannel.read());
            } while (!message.equals("exit"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (Exception e) {
			e.printStackTrace();
		} finally {
            if (serverChannel != null) serverChannel.close();
            if (localChannel != null) localChannel.close();
        }
    }
    
	private void startWriterListener() throws Exception {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ServerSocket localServerSocket = new ServerSocket(localPort);
		            System.out.println("waiting writer connection");
					localChannel = new StringSocket(localServerSocket.accept());
		            System.out.println("writer connection is established");
					localServerSocket.close();
					while(true) {
						String message = localChannel.read();
						serverChannel.write(message);
						if (message.equals("exit")) {
							localChannel.close();
							System.exit(0);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (localChannel != null) {
						localChannel.close();
					}
				}
			}
		}).start();
	}
}
